from django.contrib import admin
from .models import Book, BookInstance, Author

class BookInstanceInline(admin.TabularInline):
    model = BookInstance

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'isbn')
    inlines = [BookInstanceInline]

@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
    list_display = ('id', 'book', 'borrower', 'due_back', 'status')
    list_filter = ('status', 'due_back')
    search_fields = ('id', 'book__title')
    actions = ['renew_bookinstance']

    def renew_bookinstance(self, request, queryset):
        """续借图书，将归还日期延长 30 天"""
        from datetime import timedelta
        for bookinst in queryset:
            if bookinst.due_back:
                bookinst.renew(bookinst.due_back + timedelta(days=30))
        self.message_user(request, "续借成功。")
    renew_bookinstance.short_description = "续借图书"

admin.site.register(Author)
